import os
import sys
from tools.lbs_utils import *
"""
生成订单经纬度坐标
1.导出路程锁定时间为2小时的订单
"""


def get_yesterday(diff_days=1):
    today = datetime.date.today()
    one_day = datetime.timedelta(days=diff_days)
    ret_day = today - one_day
    return ret_day.strftime("%Y-%m-%d")


def get_half_hour(se):
    half_hour = se['reserve_tm'].hour * 2
    minutes = math.ceil(se['reserve_tm'].minute/30)
    half_hour += minutes
    return half_hour


def get_location(se):
    location = geo_to_location(se['srv_addr'], se['city_id'])
    if location is not None:
        lon, lat = position_to_points(location)
    else:
        lon = None
        lat = None
    return lon, lat


if __name__ == "__main__":
    # 以下是城市地理位置映射，替换成你自己的
    # 北京、上海、杭州、深圳
    city_cds = [[1, 22], [895, 917], [3812, 3826], [4994, 5001]]
    # 服务项目
    cate_cds = ['tag_mei_rong', 'tag_mei_jia', 'tag_mei_jie', 'tag_wei_zheng']
    # 分城市+类目
    try:
        city_id = int(sys.argv[1]) - 1
    except:
        city_id = 0
    try:
        cate_id = int(sys.argv[2]) - 1
    except:
        cate_id = 0
    try:
        day_interval = int(sys.argv[3])
    except:
        day_interval = 1
    if city_id < 0:
        city_id = 0
    if cate_id < 0:
        cate_id = 0
    if day_interval < 1:
        day_interval = 1
    yesterday = get_yesterday(day_interval)
    target_file = '/data/disp/' + yesterday + '/orders_' + str(city_id) + '_' + str(cate_id) + '.csv'

    if not os.path.isfile(target_file):
        df_orders = pd.read_csv('/data/disp/' + yesterday + '/orders.csv', error_bad_lines=False,
                                warn_bad_lines=False,
                                encoding='utf8')
        if df_orders is not None:
            try:
                df_orders.drop('Unnamed: 0', axis=1, inplace=True)
            except:
                pass
            city = city_cds[city_id]
            cate = cate_cds[cate_id]
            df_orders = df_orders[(df_orders['city_id'] >= city[0]) & (df_orders['city_id'] <= city[1]) & (
                    df_orders['prod_cate_cd'] == cate)].reset_index(drop=True)
            try:
                df_orders['reserve_tm'] = pd.to_datetime(df_orders['reserve_tm'], format='%Y-%m-%d %H:%M:%S')
                # 注意半小时刻度
                df_orders['half_hour'] = df_orders.apply(get_half_hour, axis=1)
                df_orders['start'] = df_orders['half_hour'] * 30 * 60
                df_orders['stop'] = df_orders['start'] + df_orders['prod_minute'] * 60
            except:
                pass
            try:
                df_orders['lon'], df_orders['lat'] = zip(*df_orders.apply(get_location, axis=1))
            except Exception as e:
                print(e)
            df_orders.to_csv(target_file)
            print('gen orders:' + str(len(df_orders)))
